const log4js = require('../../utils/logUtils');
const zlMediaKit = require("../../service/ZlMediaKitApi");
const constants = require("../../db/constants");
const deviceCache = require("../../db/deviceCache");
const mediaServerModel = require("../../model/mediaServer");
const channelModel = require("../../model/channel");
const moment = require("moment");
const logger = log4js.getLogger('web');


const TAG = "[ZlMediaKit Rest]";
//调用 ZLMediaKit
module.exports = {
    // 没有首页
    index: function (req, res) {
        res.send('NOT IMPLEMENTED: index');
    },
    // 读取目标媒体服务器配置信息
    getServerConfig(req, res) {
        zlMediaKit.getServerConfig(req.query.host, req.query.port, req.query.zl_secret).then((data) => {
            if (data.code === 50008) {
                data.code = constants.httpCode.ILLEGAL_PARAM.code;
            }
            res.send(data);
        }).catch((err) => {
            res.send(Object.assign(constants.httpCode.ILLEGAL_PARAM, {data: err}));
        });
    },
    // 查询rtp列表
    rtpList(req, res) {
        let serverId = req.query.media_server_id;
        zlMediaKit.listRtpServer(serverId).then((list) => {
            res.send(Object.assign(constants.httpCode.OK, {data: list}));
        }).catch((err) => {
            res.send(Object.assign(constants.httpCode.ILLEGAL_PARAM, {data: err}));
        });
    },

    isRecording(req, res){
        const camera_id = req.body.camera_id;
        const camera = deviceCache.getCameraByChannelId(camera_id);
        const serverId = camera.server_id;
        let type;
        if(camera.hasOwnProperty("type")){
            type = camera.type;
        }else{
            type = 1;
        }
        const vhost = '__defaultVhost__';
        const app = 'proxy';
        const stream = `${camera.deviceid}_${camera.channel_id}`;

        zlMediaKit.isRecording(serverId, type, vhost, app, stream).then((data) => {
            res.send(Object.assign(constants.httpCode.OK, {data: data}));
        }).catch((err) => {
            res.send(Object.assign(constants.httpCode.ILLEGAL_PARAM, {data: err}));
        });
    },
    // 读取录像文件
    async listRecordFiles(req, res) {
        const mediaType = req.query.mediaType;
        let deviceId, channelId;
        let type, hostModel, app;

        if(mediaType==='gb28181'){
            deviceId = req.query.deviceid;
            channelId = req.query.channelid;
            type = 1;
            hostModel = await mediaServerModel.getDefault();
            app = 'rtp';
        }else{
            const camera_id = req.query.camera_id;
            if(!camera_id){
                res.send(Object.assign(constants.httpCode.ILLEGAL_PARAM, {data: "camera_id is required"}));
                return;
            }
            const camera = deviceCache.getCameraById(camera_id);
            if(!camera){
                res.send(Object.assign(constants.httpCode.ILLEGAL_PARAM, {data: "camera_id is invalid"}));
                return;
            }
            deviceId = camera.deviceid;
            channelId = camera.channel_id;
            if(camera.hasOwnProperty("type")){
                type = camera.type;
            }else{
                type = 1;
            }
            hostModel = await mediaServerModel.getInfoById(camera.server_id);
            app = 'proxy';
        }
        const stream = `${deviceId}_${channelId}`;
        const vhost = '__defaultVhost__';
        const customized_path = '';
        const date = req.query.date;
        const path = `record/${app}/${stream}/${date}`;

        zlMediaKit.listRecordFiles(hostModel, type, vhost, app, stream, customized_path, date).then((list) => {
            logger.info(TAG, "调试", list, hostModel);

            let files = [];
            list.data.paths.forEach((item) => {
                const array = item.split('_');
                let tmp = {
                    fileName:item, path, deviceid:deviceId, channel_id:channelId
                };
                logger.info(TAG, 'listRecordFiles', array, tmp);
                if(array.length>=4){
                    // 20201201-00-00-00 的日期要转成moment
                    const start = moment(array[0],'YYYYMMDD-HHmmss').format('YYYY-MM-DD HH:mm:ss');
                    const end = moment(array[1],'YYYYMMDD-HHmmss').format('YYYY-MM-DD HH:mm:ss');
                    const duration = array[2];
                    const size = (array[3].replace(".mp4",''));
                    tmp = Object.assign(tmp, {start, end, duration, size});
                }
                channelModel.generateUrl(hostModel, tmp, 'proxy', '/'+date+'/'+item);
                files.push(tmp);
            });
            res.send(Object.assign(constants.httpCode.OK, {data: files}));
        }).catch((err) => {
            res.send(Object.assign(constants.httpCode.ILLEGAL_PARAM, {data: err}));
        });
    },
    // 查看流列表
    listStreams(req, res) {
        let serverId = req.query.server_id;
        zlMediaKit.listStreams(serverId).then((list) => {
            res.send(Object.assign(constants.httpCode.OK, {data: list}));
        }).catch((err) => {
            res.send(Object.assign(constants.httpCode.ILLEGAL_PARAM, {data: err}));
        });
    },

}